brute force dp number theory *2000

Please click on ads to support us..

Python Code:

n=int(input())
primes=[2,3,5,7,11,13,17,19,23,29]
def f(n,i):
    if n==1:
    return 1
  if i==10:
    return 10**18
  ans=10**18
  for j in range(2,n+1):
    if n%j==0:
      ans=min(ans,primes[i]**(j-1)*f(n//j,i+1))
  return ans
print(f(n,0))

C++ Code:

#include<bits/stdc++.h>
#include<iostream>
using namespace std;
typedef long long ll;
typedef long double ld;
const int N = 2e3 + 5;
const long long INF = 1e18 + 1; 
int n,m,q,timer,k;
long long dp[N + 1][N + 1];
long long a[N + 1][N + 1];
int pw[N + 1];
int p[9] = {2,3,5,7,11,13,17,19,23};
long long f(int n,int k){
      if(n == 1) return 1; 
      if(k < 0) return INF; 
      if(dp[n][k]) return dp[n][k]; 
      long long ans = f(n,k - 1);
      for(int i = 0; i <= pw[p[k]]; i++){
           if(n % (i + 1) == 0){
             long long to = f(n / (i + 1) , k - 1);
             if(to < INF / a[p[k]][i]){
                    ans = min(ans, (1ll) * to * a[p[k]][i]); 
                }
           }
      }
      return dp[n][k] = ans; 
}
int main(){
      scanf("%d",&n);
      for(int i = 0; i < 9; i++){
           a[p[i]][0] = 1; 
           while((long long) a[p[i]][pw[p[i]]] < INF / p[i]){
              pw[p[i]]++;
              a[p[i]][pw[p[i]]] = (1ll) * a[p[i]][pw[p[i]] - 1] * p[i]; 
           }
      }
      long long ans = f(n,8);
      printf("%lld \n",ans);
}


Comments

Submit
0 Comments
More Questions

1581A - CQXYM Count Permutations
337A - Puzzles
495A - Digital Counter
796A - Buying A House
67A - Partial Teacher
116A - Tram
1472B - Fair Division
1281C - Cut and Paste
141A - Amusing Joke
112A - Petya and Strings
677A - Vanya and Fence
1621A - Stable Arrangement of Rooks
472A - Design Tutorial Learn from Math
1368A - C+=
450A - Jzzhu and Children
546A - Soldier and Bananas
32B - Borze
1651B - Prove Him Wrong
381A - Sereja and Dima
41A - Translation
1559A - Mocha and Math
832A - Sasha and Sticks
292B - Network Topology
1339A - Filling Diamonds
910A - The Way to Home
617A - Elephant
48A - Rock-paper-scissors
294A - Shaass and Oskols
1213A - Chips Moving
490A - Team Olympiad